//
//  ImageCollectCollectionCell.m
//  ArtDog
//
//  Created by dllo on 16/9/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ImageCollectCollectionCell.h"
#import "UIImageView+WebCache.h"
#import "NSString+Common.h"
#import "UIView+Common.h"
#import "ZWYNetTool.h"
#import "HLMacro.h"
#import "ReminderView.h"
#import "CommunityPicture.h"
#import "ImageCollectViewController.h"
#import "CommunityWriteTopicController.h"
#import "BaseTableView.h"

@interface ImageCollectCollectionCell ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *collectImage;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIImageView *cloudImage;
@property (weak, nonatomic) IBOutlet UIImageView *deleteImage;

@end

@implementation ImageCollectCollectionCell

- (void)awakeFromNib {
    [super awakeFromNib];
    _isCollectPage = NO;
}

- (void)setPictureModel:(CommunityPicture *)pictureModel
{
    _pictureModel = pictureModel;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:pictureModel.picPath] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    if (GETCOLLECTIMAGE == nil) {
        SETCOLLECTIMAGE([NSDictionary dictionary]);
    }
    if ([GETCOLLECTIMAGE objectForKey:_pictureModel.picPath] || _isCollectPage == YES) {
        _collectImage.image = [UIImage imageNamed:@"collect_red"];
    } else {
        _collectImage.image = [UIImage imageNamed:@"love"];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(collectAction:)];
    [_collectImage addGestureRecognizer:tap];
}

- (void)setAsset:(PHAsset *)asset
{
    _asset = asset;
    PHImageManager *imageManager = [[PHImageManager alloc]init];
    [imageManager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        if (result) {
            _imageView.image = result;
        }
    }];
    _collectImage.hidden = YES;
    _cloudImage.hidden = YES;
    _deleteImage.hidden = NO;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteAction:)];
    [_deleteImage addGestureRecognizer:tap];
    
}

- (void)deleteAction:(UITapGestureRecognizer *)tap
{
    ImageCollectViewController *vc = (ImageCollectViewController *)[self getVCRecently];
    UICollectionView *collectionView = (UICollectionView *)self.superview;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除此图片？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSInteger index = 0;
        for (PHAsset *asset in vc.imageArray) {
            if ([asset isEqual:_asset]) {
                [vc.imageArray removeObjectAtIndex:index];
                break;
            }
            index++;
        }
        CommunityWriteTopicController *writeVC = vc.navigationController.viewControllers[1];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [writeVC.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [collectionView reloadData];
        if (writeVC.imageArray.count == 0) {
            [vc.navigationController popViewControllerAnimated:YES];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:confirmAction];
    [vc presentViewController: alert animated:YES completion:^{
        
    }];
}

- (void)collectAction:(UITapGestureRecognizer *)tap
{
    if (![self noLoginSkipLoginPage]) {
        if ([_collectImage.image isEqual:[UIImage imageNamed:@"love"]]) {
            NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/user/pictureCollection"] andParams:@{@"picPath": _pictureModel.picPath, @"token": [NSString getUserDefaultToken], @"sourceType": @"0", @"type": @"0"}];
            [ZWYNetTool POST:urlString andBody:nil andBodyStyle:ZWYBodyString andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
                [ReminderView reminderWithSuperView:self.contentView andTitle:@"收藏成功" andPosition:HLAlertViewPositionCenter];
                NSMutableDictionary *collectDic = [GETCOLLECTIMAGE mutableCopy];
                [collectDic setValue:_pictureModel.picPath forKey:_pictureModel.picPath];
                _collectImage.image = [UIImage imageNamed:@"collect_red"];
                SETCOLLECTIMAGE(collectDic);
            } andFailureBlock:^(NSError *error) {
                [ReminderView reminderWithSuperView:self.contentView andTitle:@"收藏失败" andPosition:HLAlertViewPositionCenter];
                NSLog(@"%@", error);
            }];
        } else {
            if (_isCollectPage) {
                NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/user/pictureCollection"] andParams:@{@"picPath": _pictureModel.picPath, @"token": [NSString getUserDefaultToken], @"sourceType": @"0", @"type": @"1", @"pictureId": [NSString stringWithFormat:@"%@", _pictureModel.idField]}];
                [ZWYNetTool POST:urlString andBody:nil andBodyStyle:ZWYBodyString andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
                    NSMutableDictionary *collectDic = [GETCOLLECTIMAGE mutableCopy];
                    [collectDic removeObjectForKey:_pictureModel.picPath];
                    SETCOLLECTIMAGE(collectDic);
                    _collectImage.image = [UIImage imageNamed:@"love"];
                    ImageCollectViewController *vc = (ImageCollectViewController *)[self getVCRecently];
                    [vc.navigationController popViewControllerAnimated:YES];
                    [vc.delegate cancelCollect:_pictureModel];
                } andFailureBlock:^(NSError *error) {
                    [ReminderView reminderWithSuperView:self.contentView andTitle:@"取消收藏失败" andPosition:HLAlertViewPositionCenter];
                    NSLog(@"%@", error);
                }];
                
            } else {
                [ReminderView reminderWithSuperView:self.contentView andTitle:@"已经收藏该图片" andPosition:HLAlertViewPositionCenter];
            }
            
        }
    } else {
        UIViewController *vc = [self getVCRecently];
        [vc.navigationController popViewControllerAnimated:YES];
    }
}

@end
